/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package fr.adama.controller;

import fr.adama.exception.BulletinFileNotFoundException;
import fr.adama.controller.util.TypeDownload;
import fr.adama.dto.BulletinPaieDTO;
import fr.adama.entite.BulletinPaie;
import fr.adama.entite.typePerso.EtatBulletin;
import fr.adama.exception.ArchiveException;
import fr.adama.exception.ControllerException;
import fr.adama.service.BulletinPaieService;
import fr.adama.service.ContratService;
import fr.adama.util.DateFormatFactory;
import fr.adama.util.ZipUtil;
import java.io.File;
import java.io.IOException;
import java.util.Date;
import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.io.FileUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.support.RequestContextUtils;

/**
 *
 * @author mini-john
 */
@Controller
public class FileController {
    
    private static final Logger logger = LoggerFactory.getLogger(FileController.class);
    @Autowired
    BulletinPaieService bulletinPaieService;
    @Autowired
    ContratService contratService;
    
    @RequestMapping(value = "/download/{type}/get.do", method = RequestMethod.GET)
    public HttpEntity<byte[]> getFile(@PathVariable("type") TypeDownload type, HttpServletRequest request, @RequestParam("id") Long id, HttpServletResponse response) throws ControllerException, IOException, ArchiveException {
        String  filename = "";
        
        File file;
        switch (type) {
            case Bulletin:
                
                BulletinPaieDTO bulletin = bulletinPaieService.getById(id, BulletinPaie.class, BulletinPaieDTO.class);
                logger.info("Telechargement du bulletin d'id {}", bulletin.getId());
                if (bulletin == null) {
                    logger.error("Il n'y a pas de bulletin pour id=" + id);
                    throw new ControllerException("Il n'y a pas de bulletin pour id=" + id);
                }
                filename = bulletin.getContrat().getAdherent().getNomPrenom() + "-" + bulletin.getContrat().getEmploye().getNom() + "-" + bulletin.getContrat().getEmploye().getPrenom() + "-" + bulletin.getAnnee() + "-" + bulletin.getMois() + ".pdf";
                file = ZipUtil.getBulletinPDFFromZip(new File(bulletin.getPathToPdf()));
                if (!file.exists()) {
                    logger.error("Le fichier du bulletin {} n'exite pat ", bulletin.getId());
                    throw new BulletinFileNotFoundException("Fichier manquant " + bulletin.getPathToPdf(), bulletin);
                    
                }
                file.deleteOnExit();
                bulletin.setEtatBulletin(EtatBulletin.imprime);
                bulletinPaieService.update(bulletin, BulletinPaie.class);
                break;
            case Facture:
                throw new ControllerException("Pas encore implemente");
            //  break;
            case Contrat:
                throw new ControllerException("Pas encore implemente");
            // break;
            default:
                throw new ControllerException("Type non pris en charge " + type);
        }
        
        ServletContext context = RequestContextUtils.getWebApplicationContext(request).getServletContext();
        String mimetype = context.getMimeType(file.getAbsolutePath());
        HttpHeaders header = new HttpHeaders();
        header.setContentType(new MediaType(mimetype.split("/")[0], mimetype.split("/")[1]));
        header.set("Content-Disposition",
                "attachment; filename=" + filename);
        header.setContentLength(file.length());
        
        return new HttpEntity<>(FileUtils.readFileToByteArray(file), header);
    }
    
    @RequestMapping(value = "/download/{type}/getAllForPrint.do", method = RequestMethod.GET)
    public HttpEntity<byte[]> getFileAllForPrint(@PathVariable("type") TypeDownload type, @DateTimeFormat(pattern = "MM yyyy") @RequestParam("periode") Date periode, HttpServletRequest request, HttpServletResponse response) throws ControllerException, IOException, ArchiveException {
        String  filename = "";
        
        File file;
        
        switch (type) {
            case Bulletin:              
                file = bulletinPaieService.getFileAllBulletinForPrint(periode);
                filename = "Bulletin " + DateFormatFactory.getDateFormatPeriode().format(periode) + ".pdf";
                break;
            case Facture:
                throw new ControllerException("Pas encore implemente");
            //  break;
            case Contrat:
                throw new ControllerException("Pas encore implemente");
            // break;
            default:
                throw new ControllerException("Type non pris en charge " + type);
        }
        
        ServletContext context = RequestContextUtils.getWebApplicationContext(request).getServletContext();
        String mimetype = context.getMimeType(file.getAbsolutePath());
        HttpHeaders header = new HttpHeaders();
        header.setContentType(new MediaType(mimetype.split("/")[0], mimetype.split("/")[1]));
        header.set("Content-Disposition",
                "attachment; filename=" + filename);
        header.setContentLength(file.length());
        
        return new HttpEntity<>(FileUtils.readFileToByteArray(file), header);
    }
    
    @RequestMapping("/404.do")
    public ModelAndView error404() {
        return new ModelAndView("404");
    }
    
}
